using System;
using UnityEngine;

namespace Locomotion
{
    public class Mover : MonoBehaviour
    {
        [SerializeField] private float moveSpeed = 4f;
        
        private bool IsFrozen => _freezeTimer > 0f;
        
        private float _freezeTimer = 0f;
        
        private Rigidbody2D _rigidbody2D;

        private Vector2 _moveDirection;


        private void Awake()
        {
            _rigidbody2D = GetComponent<Rigidbody2D>();
        }

        private void Update()
        {
            if (_freezeTimer > 0f)
                _freezeTimer -= Time.deltaTime;
        }

        private void FixedUpdate()
        {
            if (IsFrozen) return;
            
            _rigidbody2D.velocity = moveSpeed * _moveDirection;
        }

        public void Move(Vector2 moveDirection)
        {
            _moveDirection = moveDirection;
        }

        public void StopMoving()
        {
            _moveDirection = Vector2.zero;
        }

        public void Knock(Vector2 direction, float force, float freezeTime)
        {
            _freezeTimer = freezeTime;
            
            _rigidbody2D.velocity = Vector2.zero;
            _rigidbody2D.AddForce(force * direction, ForceMode2D.Impulse);
        }
    }
}